package mac.filter;
import java.io.*;
import java.net.*;

public class Server extends Thread {
    public final static int DEFAULT_PORT = 8030;
    protected int port;
    protected ServerSocket listen_socket;

    public static void fail(Exception e, String msg) {
	System.err.println(msg + ":" + e);
	System.exit(1);
    }

    public Server(int port) {
	if(port == 0) port = DEFAULT_PORT;
	this.port = port;
	try {	
		listen_socket = new ServerSocket(port);
	}
	catch(IOException e) {fail(e,"Exception creating server socket");}
	System.out.println("Server:listening on port " + port);
	this.start();
    }

    public void run() {
	try {
	    while(true) {
		    Socket client_socket = listen_socket.accept();
		    Connection c = new Connection(client_socket);
	    }
	}
	catch(IOException e) {
	    fail(e, "Exception while listening for connections");
	}
    }
    public static void main(String[] args)
    {
	int port = 0;
	if(args.length == 1) {
	    try {
		    port = Integer.parseInt(args[0]);
	    }
	    catch(NumberFormatException e){port = 0;}
	    new Server(port);
	} else new Server(port);
    }
}

class Connection extends Thread {
    protected Socket client;
    protected DataInputStream in;
    protected ObjectInputStream o_in;

    public Connection(Socket client_socket) {
	client = client_socket;
	try {
	    in = new DataInputStream(client.getInputStream());
	    o_in = new ObjectInputStream(in);
	}
	catch(IOException e) {
	    try{client.close();} catch(IOException e2){}
	    System.err.println(
		    "Exception while getting socket streams: " +e);
		return;
	}
	this.start();
    }

    public void run() {
	String line;
	StringBuffer revline;
	int len;
	SnapshotObj s_o;

	try {
	    for(;;) {
		    s_o = (SnapshotObj)o_in.readObject(); 
		    System.out.println(s_o);
	    }
	}
	catch(EOFException e){}
	catch(IOException e){System.err.println(e);}
	catch(ClassNotFoundException e){System.err.println(e);}
	finally{ try {client.close();} catch(IOException e2){}}
    }
}
